package com.sc.test.gps;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.sc.test.R;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Shen Chao
 * Created by 2018-12-05
 */
public class GPSActivity extends AppCompatActivity {
    @BindView(R.id.tv_content)
    TextView tvContent;

    private static final int REQUEST_CAMERA = 100;

    double longitude;
    double latitude;
    double accuracy;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_open_carema, R.id.btn_take_pic, R.id.btn_gps, R.id.btn_gps_new, R.id.btn_dail_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_open_carema:
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivity(intent);
                break;
            case R.id.btn_take_pic:
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                    // 设置系统相机拍照后的输出路径
                    // 创建临时文件
                    File tempFile = createTmpFile(this, "/temp/pictures");
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(cameraIntent, REQUEST_CAMERA);
                } else {
                    Toast.makeText(this, "没有相机", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_gps:
                //获取用户手机的位置服务
                LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
                MyLocationListener locationListener = new MyLocationListener();
//                //查询条件
//                Criteria criteria = new Criteria();
//                //精确度   最高
//                criteria.setAccuracy(Criteria.ACCURACY_FINE);
//                //是否运行产生开销  默认为false
//                criteria.setCostAllowed(true);
//                //电量的消耗-高电量  默认为int mPowerRequirement = NO_REQUIREMENT //不做特殊处理
//                criteria.setPowerRequirement(Criteria.POWER_HIGH);
//                String provider = lm.getBestProvider(criteria, true);
//                System.out.println("位置提供者:" + provider);

                String[] PERMISSIONS_GPRS = {"android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"};
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, PERMISSIONS_GPRS, 1);
                } else {
                    Location location = null;
                    String providerResult = "";
                    List<String> providers = lm.getProviders(true);
                    for (String provider : providers) {
                        Location l = lm.getLastKnownLocation(provider);
                        if (l == null) {
                            continue;
                        }
                        if (location == null || l.getAccuracy() < location.getAccuracy()) {
                            location = l;
                            providerResult = provider;
                            tvContent.append("定位方式:" + provider);
                            tvContent.append("\n");
                        }
                    }
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                    accuracy = location.getAccuracy();
                    String result = "经度:" + longitude + "\n" + "纬度:" + latitude + "\n精确度:" + accuracy + "m";
                    tvContent.append("原生：" + result);
                    tvContent.append("\n");
                    lm.requestLocationUpdates(providerResult, 0, 0, locationListener);
                }
                break;
            case R.id.btn_gps_new:
                ModifyOffset modifyOffSet = null;
                try {
                    InputStream is = getAssets().open("axisoffset.dat");
                    modifyOffSet = ModifyOffset.getInstance(is);
                    PointDouble marsPoint = modifyOffSet.s2c(new PointDouble(longitude, latitude));
                    tvContent.append("火星：" + marsPoint.toString());
                    tvContent.append("\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.btn_dail_phone:
                Intent dialIntent = new Intent(Intent.ACTION_DIAL);
                startActivity(dialIntent);
                break;
        }
    }

    private File createTmpFile(Context context, String filePath) {
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        String externalStorageState = Environment.getExternalStorageState();
        File dir = new File(Environment.getExternalStorageDirectory() + filePath);
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            if (!dir.exists()) {
                dir.mkdirs();
            }
            return new File(dir, timeStamp + ".jpg");
        } else {
            File cacheDir = context.getCacheDir();
            return new File(cacheDir, timeStamp + ".jpg");
        }
    }

    private class MyLocationListener implements LocationListener {

        //当位置发生变化的时候 调用.
        @Override
        public void onLocationChanged(Location location) {
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();
            double accuracy = location.getAccuracy();
            String result = "经度:" + longitude + "\n" + "纬度:" + latitude + "\n精确度:" + accuracy + "m";
        }

        //位置提供者状态变化的时候 调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        //当某个位置提供者 被启用
        @Override
        public void onProviderEnabled(String provider) {

        }

        //当某个位置提供者 被禁用
        @Override
        public void onProviderDisabled(String provider) {

        }

    }
}
